var _excluded = ["value", "onChange", "suffix", "style", "editable", "className", "type", "tooltip", "observer", "enterButton", "id"],
  _excluded2 = ["outRef", "style", "placeholder", "value", "onChange", "allowClear"];
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { SearchOutlined, SwapRightOutlined } from '@ant-design/icons';
import { Input as AntInput, InputNumber as AntInputNumber, Space } from 'antd';
import useCursor from 'rc-input-number/es/hooks/useCursor';
import React from 'react';
import { Tooltip } from "../functionalComponent";
import { compHoc, getGlobalConfig, iup, IUPComponent, useExtendRef, useLayoutUpdateEffect } from "../util";
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function getInput(inputComponent) {
  var trigger = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  return /*#__PURE__*/function (_IUPComponent) {
    _inherits(_class2, _IUPComponent);
    var _super = _createSuper(_class2);
    function _class2(props) {
      var _this;
      _classCallCheck(this, _class2);
      _this = _super.call(this, props);
      _defineProperty(_assertThisInitialized(_this), "parentEl", null);
      _defineProperty(_assertThisInitialized(_this), "inputEl", null);
      _defineProperty(_assertThisInitialized(_this), "Comp", inputComponent);
      _defineProperty(_assertThisInitialized(_this), "lastInputTxt", '');
      _defineProperty(_assertThisInitialized(_this), "onInputChange", function (e) {
        var currentValue = e && e.target ? e.target.value : e;
        var value = currentValue;
        if (_this.Comp !== AntInputNumber && _this.props.parser) {
          value = _this.props.parser(value);
        }
        if (_this.props.hasOwnProperty('value')) {
          var _this$props$onChange, _this$props;
          // 外部受控
          _this.state.value = value;
          (_this$props$onChange = (_this$props = _this.props).onChange) === null || _this$props$onChange === void 0 || _this$props$onChange.call(_this$props, value);
        } else {
          _this.setValue(value);
        }
        _this.innerNotify([value], 'onChange').then();
      });
      /**
       * 过滤多余的属性
       * @param inputProps
       * @param type input类型
       */
      _defineProperty(_assertThisInitialized(_this), "getInputProps", function (inputProps, type) {
        var _inputProps$allowClea;
        inputProps.allowClear = (_inputProps$allowClea = inputProps.allowClear) !== null && _inputProps$allowClea !== void 0 ? _inputProps$allowClea : true;
        if (_this.Comp === AntInputNumber) {
          delete inputProps.allowClear;
          var precision = _this.getPrecision(true);
          inputProps.precision = _this.getPrecision();
          inputProps.controls = false;
          if (!inputProps.formatter && !inputProps.parser) {
            if (type === 'rate') {
              inputProps.formatter = function (value) {
                return iup.thousandNumber(iup.numberPrecision(value * 100), {
                  precision: iup.getCursorPosition() > -1 ? undefined : precision
                });
              };
              inputProps.parser = function (value) {
                var v = +value.replace(/\$\s?|(,*)/g, '');
                return iup.isNumber(precision) ? +iup.numberPrecision(v / 100).toFixed(precision + 2) : iup.numberPrecision(v / 100);
              };
            } else {
              inputProps.formatter = function (value) {
                return iup.thousandNumber(value, {
                  precision: iup.getCursorPosition() > -1 ? undefined : precision
                });
              };
              inputProps.parser = function (value) {
                return value.replace(/\$\s?|(,*)/g, '');
              };
            }
          }
        } else if (type) {
          inputProps.type = type;
        }
        if (_this.Comp !== AntInputNumber) {
          delete inputProps.formatter;
          delete inputProps.parser;
        }
        if (_this.Comp === AntInput.Password) {
          if (inputProps.disabled) {
            inputProps.visibilityToggle = false;
          }
        }
        if (trigger) {
          delete inputProps.onTrigger;
          delete inputProps.editable;
        }
        if (inputProps.disabled) {
          delete inputProps.allowClear;
          inputProps.placeholder = '';
        }
        if (inputProps.maxLength && !inputProps.count) {
          var max = inputProps.maxLength;
          inputProps.count = {
            show: false,
            max: max,
            strategy: function strategy(txt) {
              if (iup.strLen(txt) <= max) {
                _this.lastInputTxt = txt;
              } else {
                var tmp = txt.substring(0, max);
                while (tmp && iup.strLen(tmp) > max) {
                  tmp = tmp.substring(0, tmp.length - 1);
                }
                _this.lastInputTxt = tmp;
              }
              return iup.strLen(txt);
            },
            exceedFormatter: function exceedFormatter() {
              return _this.lastInputTxt;
            }
          };
          delete inputProps.maxLength;
        }
        return inputProps;
      });
      _defineProperty(_assertThisInitialized(_this), "elClick", function (e) {
        if (_this.props.disabled) {
          return;
        }
        if (_this.editable) {
          if (!iup.closest(e.target, function (el) {
            return el.classList.contains('ant-input-clear-icon');
          }) && iup.closest(e.target, function (el) {
            return el.classList.contains('ant-input-suffix');
          })) {
            var _this$props$onTrigger, _this$props2;
            (_this$props$onTrigger = (_this$props2 = _this.props).onTrigger) === null || _this$props$onTrigger === void 0 || _this$props$onTrigger.call(_this$props2, e);
          }
        } else if (!iup.closest(e.target, function (el) {
          return el.classList.contains('ant-input-clear-icon');
        })) {
          var _this$props$onTrigger2, _this$props3;
          (_this$props$onTrigger2 = (_this$props3 = _this.props).onTrigger) === null || _this$props$onTrigger2 === void 0 || _this$props$onTrigger2.call(_this$props3, e);
        }
      });
      _defineProperty(_assertThisInitialized(_this), "dbClick", function (e) {
        var _this$props$onTrigger3, _this$props4;
        if (_this.props.disabled) {
          return;
        }
        (_this$props$onTrigger3 = (_this$props4 = _this.props).onTrigger) === null || _this$props$onTrigger3 === void 0 || _this$props$onTrigger3.call(_this$props4, e);
      });
      _defineProperty(_assertThisInitialized(_this), "getTooltipRender", function (title, tooltip) {
        return function () {
          if (iup.isBoolean(tooltip)) {
            return title;
          } else if (iup.isFunction(tooltip)) {
            return tooltip(title);
          }
          return tooltip;
        };
      });
      _defineProperty(_assertThisInitialized(_this), "getFormatValue", function (type) {
        return _this.props.formatter && _this.Comp !== AntInputNumber ? _this.props.formatter(_this.state.value || '') : _this.state.value;
      });
      _this.state.value = props.defaultValue;
      if (_this.props.type === 'number' && _this.Comp !== AntInputNumber) {
        _this.Comp = AntInputNumber;
      }
      return _this;
    }
    _createClass(_class2, [{
      key: "editable",
      get: function get() {
        var _this$props$editable, _this$props5;
        return (_this$props$editable = (_this$props5 = this.props) === null || _this$props5 === void 0 ? void 0 : _this$props5.editable) !== null && _this$props$editable !== void 0 ? _this$props$editable : true;
      }
    }, {
      key: "setValue",
      value: function setValue(value, cb) {
        var _this2 = this;
        if (this.state.value === value) {
          return;
        }
        this.setState({
          value: value
        }, function () {
          var _this2$props$onChange, _this2$props;
          (_this2$props$onChange = (_this2$props = _this2.props).onChange) === null || _this2$props$onChange === void 0 || _this2$props$onChange.call(_this2$props, value);
          cb === null || cb === void 0 || cb(value);
        });
      }
    }, {
      key: "getValue",
      value: function getValue() {
        return this.state.value;
      }
    }, {
      key: "getPrecision",
      value: function getPrecision() {
        var calc = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
        var _this$props6 = this.props,
          type = _this$props6.type,
          precision = _this$props6.precision;
        if (['percent', 'prc', 'amt', 'amount', 'qty', 'rate'].includes(type) && iup.isNumber(getGlobalConfig().default.precision[type])) {
          var p = getGlobalConfig().default.precision[type];
          if (calc && type === 'rate') {
            return Math.max(0, p - 2);
          }
          return p;
        }
        if (!iup.isNullOrEmpty(precision) && ['number', 'prc', 'amt', 'amount', 'qty', 'rate', 'percent'].includes(type)) {
          var tmp = Number(precision);
          return iup.isNumber(tmp) ? type === 'rate' && calc ? Math.max(0, tmp - 2) : tmp : undefined;
        }
        return precision;
      }
    }, {
      key: "componentDidMount",
      value: function componentDidMount() {
        var _this$outRef$current;
        this.inputEl = ((_this$outRef$current = this.outRef.current) === null || _this$outRef$current === void 0 ? void 0 : _this$outRef$current.input) || this.outRef.current;
        if (trigger) {
          var _this$inputEl;
          this.parentEl = ((_this$inputEl = this.inputEl) === null || _this$inputEl === void 0 ? void 0 : _this$inputEl.parentElement) || this.inputEl || this.outRef.current;
          this.parentEl.addEventListener('click', this.elClick);
          if (this.editable && this.inputEl) {
            this.inputEl.addEventListener('dblclick', this.dbClick);
          }
        }
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        if (trigger) {
          var _this$parentEl;
          (_this$parentEl = this.parentEl) === null || _this$parentEl === void 0 || _this$parentEl.removeEventListener('click', this.elClick);
          if (this.editable) {
            var _this$inputEl2;
            (_this$inputEl2 = this.inputEl) === null || _this$inputEl2 === void 0 || _this$inputEl2.removeEventListener('dblclick', this.dbClick);
          }
        }
      }
    }, {
      key: "render",
      value: function render() {
        var _this3 = this;
        var Comp = this.Comp;
        var _ref = this.props,
          value = _ref.value,
          onChange = _ref.onChange,
          suffix = _ref.suffix,
          _ref$style = _ref.style,
          style = _ref$style === void 0 ? {} : _ref$style,
          editable = _ref.editable,
          className = _ref.className,
          _ref$type = _ref.type,
          type = _ref$type === void 0 ? Comp === AntInputNumber ? 'number' : 'text' : _ref$type,
          tooltip = _ref.tooltip,
          observer = _ref.observer,
          enterButton = _ref.enterButton,
          id = _ref.id,
          inputProps = _objectWithoutProperties(_ref, _excluded);
        var suffixIcon = suffix || (trigger && !inputProps.disabled ? /*#__PURE__*/_jsx(SearchOutlined, {
          style: {
            cursor: 'pointer',
            opacity: 0.45,
            fontSize: 14
          }
        }) : null);
        var formatValue = this.getFormatValue(type);
        var innerProps = this.getInputProps(inputProps, type);
        if (Comp === AntInput.Search && !enterButton && !inputProps.disabled) {
          innerProps.suffix = formatValue ? /*#__PURE__*/_jsx(_Fragment, {}) : /*#__PURE__*/_jsx(SearchOutlined, {
            style: {
              cursor: 'pointer',
              fontSize: 14,
              opacity: 0.45
            }
          });
          innerProps.enterButton = null;
          innerProps.className = iup.classNames(className, "iup-".concat(type), 'hidden-addon-icon', {
            'iup-trigger-input': trigger && editable === false
          });
        }
        var renderInput = function renderInput() {
          var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            recordCursor = _ref2.recordCursor;
          return /*#__PURE__*/_jsx(Comp, _objectSpread(_objectSpread({
            ref: _this3.outRef,
            className: iup.classNames(className, "iup-".concat(type), {
              'iup-trigger-input': trigger && editable === false
            }),
            value: formatValue,
            style: _objectSpread({
              width: '100%'
            }, style),
            suffix: suffixIcon
          }, innerProps), {}, {
            onChange: function onChange(e) {
              recordCursor === null || recordCursor === void 0 || recordCursor();
              _this3.onInputChange(e);
            }
          }));
        };
        if ([AntInput].includes(Comp) && this.props.formatter) {
          return /*#__PURE__*/_jsx(InnerInput, {
            renderInput: renderInput,
            value: formatValue,
            ins: this
          });
        }
        return tooltip ? /*#__PURE__*/_jsx(Tooltip, {
          title: this.getTooltipRender(formatValue || innerProps.placeholder, tooltip),
          children: renderInput()
        }) : renderInput();
      }
    }], [{
      key: "getDerivedStateFromProps",
      value: function getDerivedStateFromProps(nextProps, prevState) {
        return IUPComponent.propsToState(nextProps, prevState, ['value']);
      }
    }]);
    return _class2;
  }(IUPComponent);
}
function InnerInput(_ref3) {
  var _ins$outRef$current;
  var renderInput = _ref3.renderInput,
    value = _ref3.value,
    ins = _ref3.ins;
  var _ins$props = ins.props,
    placeholder = _ins$props.placeholder,
    tooltip = _ins$props.tooltip,
    formatter = _ins$props.formatter;
  var _useCursor = useCursor((_ins$outRef$current = ins.outRef.current) === null || _ins$outRef$current === void 0 ? void 0 : _ins$outRef$current.input, true),
    _useCursor2 = _slicedToArray(_useCursor, 2),
    recordCursor = _useCursor2[0],
    restoreCursor = _useCursor2[1];
  useLayoutUpdateEffect(function () {
    formatter && value && restoreCursor();
  }, [value]);
  return tooltip ? /*#__PURE__*/_jsx(Tooltip, {
    title: ins.getTooltipRender(value || placeholder, tooltip),
    children: renderInput({
      recordCursor: recordCursor
    })
  }) : renderInput({
    recordCursor: recordCursor
  });
}
export var Input = compHoc(getInput(AntInput));

// prc 是单价 amt是合价 qty是工程量，rate是百分比
export var InputNumber = compHoc(getInput(AntInputNumber));
export var TextArea = compHoc(getInput(AntInput.TextArea));
export var Password = compHoc(getInput(AntInput.Password));
export var Search = compHoc(getInput(AntInput.Search));
export var InputTrigger = compHoc(getInput(AntInput, true));
export var InputNumberRange = compHoc(function (_ref4) {
  var outRef = _ref4.outRef,
    style = _ref4.style,
    placeholder = _ref4.placeholder,
    value = _ref4.value,
    onChange = _ref4.onChange,
    allowClear = _ref4.allowClear,
    props = _objectWithoutProperties(_ref4, _excluded2);
  var getValueArr = function getValueArr() {
    var tmp = iup.split(value);
    tmp[0] = tmp[0] ? +tmp[0] : null;
    tmp[1] = tmp[1] ? +tmp[1] : null;
    if (!iup.isNumber(tmp[0])) {
      tmp[0] = null;
    }
    if (!iup.isNumber(tmp[1])) {
      tmp[1] = null;
    }
    return tmp;
  };
  var placeholderArr = iup.split(placeholder);
  var vauleArr = getValueArr();
  var handleChange = function handleChange(idx) {
    return function (v) {
      var newValue = [vauleArr[0], vauleArr[1]];
      newValue[idx] = v;
      onChange === null || onChange === void 0 || onChange(newValue);
    };
  };
  useExtendRef(outRef, function () {
    return {
      getValue: function getValue() {
        return getValueArr();
      },
      setValue: function setValue(v) {
        onChange === null || onChange === void 0 || onChange(v);
      }
    };
  });
  return /*#__PURE__*/_jsxs(Space.Compact, {
    block: true,
    style: style,
    className: "ant-input-number ant-input-number-outlined",
    children: [/*#__PURE__*/_jsx(AntInputNumber, _objectSpread(_objectSpread({}, props), {}, {
      value: vauleArr[0],
      onChange: handleChange(0),
      controls: false,
      style: {
        flex: 1,
        width: 0,
        border: 0
      },
      placeholder: placeholderArr[0]
    })), /*#__PURE__*/_jsx(SwapRightOutlined, {}), /*#__PURE__*/_jsx(AntInputNumber, _objectSpread(_objectSpread({}, props), {}, {
      controls: false,
      onChange: handleChange(1),
      style: {
        flex: 1,
        width: 0,
        border: 0
      },
      value: vauleArr[1],
      placeholder: placeholderArr[1]
    }))]
  });
});